package com.quectel.core.module.partyeducationexam.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quectel.constant.core.partyeducationexam.PartyEducationExamConstants;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partyeducationexam.dao.PartyEducationTrainingExamPersonDao;
import com.quectel.core.module.partyeducationexam.dto.PartyEducationTrainingExamDto;
import com.quectel.core.module.partyeducationexam.dto.PartyEducationTrainingExamPersonDto;
import com.quectel.core.module.partyeducationexam.dto.PartyEducationTrainingExamPersonHistoryDto;
import com.quectel.core.module.partyeducationexam.dto.ref.ExamRefPersonDto;
import com.quectel.core.module.partyeducationexam.dto.ref.PersonRefExamDto;
import com.quectel.core.module.partyeducationexam.entity.PartyEducationTrainingExamPersonEntity;
import com.quectel.core.module.partyeducationexam.service.PartyEducationTrainingExamPersonHistoryService;
import com.quectel.core.module.partyeducationexam.service.PartyEducationTrainingExamPersonService;
import com.quectel.core.module.partyeducationexam.service.PartyEducationTrainingExamService;
import com.quectel.core.module.partyeducationtraining.dto.TrainingDto;
import com.quectel.core.module.partyeducationtraining.service.TrainingService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/06/27 15:26
 */
@DubboService
public class PartyEducationTrainingExamPersonServiceImpl extends ServiceImpl<PartyEducationTrainingExamPersonDao, PartyEducationTrainingExamPersonEntity> implements PartyEducationTrainingExamPersonService{

    private static final Logger LOGGER = LoggerFactory.getLogger(PartyEducationTrainingExamPersonServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_EDUCATION_TRAINING_EXAM_PERSON_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_EDUCATION_TRAINING_EXAM_PERSON_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartyEducationTrainingExamPersonDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_EDUCATION_TRAINING_EXAM_PERSON_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PartyEducationTrainingExamPersonDao partyEducationTrainingExamPersonDao;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private TrainingService trainingService;
    @Autowired
    private PartyEducationTrainingExamService partyEducationTrainingExamService;
    @Autowired
    private PartyEducationTrainingExamPersonHistoryService partyEducationTrainingExamPersonHistoryService;


    @Override
    public void deleteByExamId(Long id) {
        partyEducationTrainingExamPersonDao.delete(new LambdaQueryWrapper<PartyEducationTrainingExamPersonEntity>()
                .eq(PartyEducationTrainingExamPersonEntity::getExamId, id));
    }

    @Override
    public PartyEducationTrainingExamPersonDto selectOneByLastExam(Long lastExamId) {
        PartyEducationTrainingExamPersonEntity partyEducationTrainingExamPersonEntity = partyEducationTrainingExamPersonDao.selectOne(new LambdaQueryWrapper<PartyEducationTrainingExamPersonEntity>()
                .eq(PartyEducationTrainingExamPersonEntity::getLastExamId, lastExamId)
                .last(SqlConstants.MYSQL_LIMIT_ONE));
        PartyEducationTrainingExamPersonDto partyEducationTrainingExamPersonDto = CopyUtils.copyObj(partyEducationTrainingExamPersonEntity, PartyEducationTrainingExamPersonDto.class);
        paddingField(partyEducationTrainingExamPersonDto);
        return partyEducationTrainingExamPersonDto;
    }

    @Override
    public PartyEducationTrainingExamPersonDto selectOne(Long examId, Long personId) {
        PartyEducationTrainingExamPersonEntity partyEducationTrainingExamPersonEntity = partyEducationTrainingExamPersonDao.selectOne(new LambdaQueryWrapper<PartyEducationTrainingExamPersonEntity>()
                .eq(PartyEducationTrainingExamPersonEntity::getExamId, examId)
                .eq(PartyEducationTrainingExamPersonEntity::getPartyPersonId, personId)
                .last(SqlConstants.MYSQL_LIMIT_ONE));
        PartyEducationTrainingExamPersonDto partyEducationTrainingExamPersonDto = CopyUtils.copyObj(partyEducationTrainingExamPersonEntity, PartyEducationTrainingExamPersonDto.class);
        paddingField(partyEducationTrainingExamPersonDto);
        return partyEducationTrainingExamPersonDto;
    }

    @Override
    public int queryExamTotal(Map<String, Object> params) {
        return partyEducationTrainingExamPersonDao.queryExamTotal(params);
    }

    @Override
    public List<PersonRefExamDto> queryPersonList(Map<String, Object> params) {
        List<PersonRefExamDto> personRefExamDtos = partyEducationTrainingExamPersonDao.queryPersonList(params);
        personRefExamDtos.forEach(this::personPaddingField);
        for (PersonRefExamDto dto : personRefExamDtos) {
            PartyEducationTrainingExamDto partyEducationTrainingExamDto = partyEducationTrainingExamService.selectCacheById(dto.getExamId());
            dto.setExam(partyEducationTrainingExamDto);

            PartyEducationTrainingExamPersonHistoryDto partyEducationTrainingExamPersonHistoryDto = partyEducationTrainingExamPersonHistoryService.selectCacheById(dto.getLastExamId());
            dto.setExamPersonHistory(partyEducationTrainingExamPersonHistoryDto);
        }
        return personRefExamDtos;
    }

    @Override
    public int queryPersonTotal(Map<String, Object> params) {
        return partyEducationTrainingExamPersonDao.queryPersonTotal(params);
    }

    private PartyPersonDto personPaddingField(PartyPersonDto dto) {
        if (dto != null) {
            PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectCacheById(dto.getPartyId());
            dto.setParty(partyOrganizationDto);
        }
        return dto;
    }

    @Override
    public void saveBatch(List<PartyEducationTrainingExamPersonDto> dtos) {
        List<PartyEducationTrainingExamPersonEntity> partyEducationTrainingExamPersonEntities = CopyUtils.copyList(dtos, PartyEducationTrainingExamPersonEntity.class);
        for (PartyEducationTrainingExamPersonEntity partyEducationTrainingExamPersonEntity : partyEducationTrainingExamPersonEntities) {
            partyEducationTrainingExamPersonEntity.setId(Snowflake.nextId());
        }
        super.saveBatch(partyEducationTrainingExamPersonEntities);
    }

    @Override
    public List<ExamRefPersonDto> queryExamList(Map<String, Object> queryExamParams) {
        List<ExamRefPersonDto> examRefPersonDtos = partyEducationTrainingExamPersonDao.queryExamList(queryExamParams);
        examRefPersonDtos.forEach(this::examPaddingField);
        return examRefPersonDtos;
    }

    private PartyEducationTrainingExamDto examPaddingField(PartyEducationTrainingExamDto dto){
        final Date currentDate = new Date();
        if (dto != null){
            PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectCacheById(dto.getPartyId());
            dto.setParty(partyOrganizationDto);

            TrainingDto trainingDto = trainingService.selectCacheById(dto.getTrainingId());
            dto.setTraining(trainingDto);

            if (PartyEducationExamConstants.StatusEnum.UNPUBLISHED.getStatus().equals(dto.getStatus())) {
                dto.setSpecificStatus(PartyEducationExamConstants.SpecificStatusEnum.UNPUBLISHED.getStatus());
            } else if (PartyEducationExamConstants.StatusEnum.PUBLISHED.getStatus().equals(dto.getStatus())) {
                if (currentDate.getTime() < dto.getStartTime().getTime()) {
                    dto.setSpecificStatus(PartyEducationExamConstants.SpecificStatusEnum.NOT_STARTED.getStatus());
                } else if (currentDate.getTime() > dto.getEndTime().getTime()) {
                    dto.setSpecificStatus(PartyEducationExamConstants.SpecificStatusEnum.ENDING.getStatus());
                } else {
                    dto.setSpecificStatus(PartyEducationExamConstants.SpecificStatusEnum.IN_PROGRESS.getStatus());
                }
            } else if (PartyEducationExamConstants.StatusEnum.CANCEL.getStatus().equals(dto.getStatus())) {
                dto.setSpecificStatus(PartyEducationExamConstants.SpecificStatusEnum.CANCEL.getStatus());
            }
        }
        return dto;
    }

    @Override
    public PartyEducationTrainingExamPersonDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_EDUCATION_TRAINING_EXAM_PERSON_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartyEducationTrainingExamPersonDto selectById(Long id){
            PartyEducationTrainingExamPersonEntity entity = partyEducationTrainingExamPersonDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,PartyEducationTrainingExamPersonDto.class));
    }

    @Override
    public List<PartyEducationTrainingExamPersonDto> queryList(Map<String,Object> params){
        List<PartyEducationTrainingExamPersonEntity> list = partyEducationTrainingExamPersonDao.queryList(params);
        List<PartyEducationTrainingExamPersonDto> result =  CopyUtils.copyList(list,PartyEducationTrainingExamPersonDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<PartyEducationTrainingExamPersonDto> queryListWithoutPadding(Map<String,Object> params){
        List<PartyEducationTrainingExamPersonEntity> list = partyEducationTrainingExamPersonDao.queryList(params);
        return CopyUtils.copyList(list,PartyEducationTrainingExamPersonDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartyEducationTrainingExamPersonDto paddingField(PartyEducationTrainingExamPersonDto dto){
        if (dto != null){

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return partyEducationTrainingExamPersonDao.queryTotal(params);
    }

    @Override
    public Long save(PartyEducationTrainingExamPersonDto dto){
        PartyEducationTrainingExamPersonEntity entity = CopyUtils.copyObj(dto,PartyEducationTrainingExamPersonEntity.class);
        entity.setId(Snowflake.nextId());
        partyEducationTrainingExamPersonDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartyEducationTrainingExamPersonDto dto){
        PartyEducationTrainingExamPersonEntity entity = CopyUtils.copyObj(dto,PartyEducationTrainingExamPersonEntity.class);

        partyEducationTrainingExamPersonDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartyEducationTrainingExamPersonDto dto) {
       PartyEducationTrainingExamPersonEntity entity = CopyUtils.copyObj(dto,PartyEducationTrainingExamPersonEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, partyEducationTrainingExamPersonDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partyEducationTrainingExamPersonDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
